﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace Sprout.Core.Utils
{
    public class FileHelper
    {
        /// <summary>
        /// 根据文件路径获取后缀名
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <returns></returns>
        public static string GetSuffix(string path)
        {
            if (string.IsNullOrEmpty(path)) return "";
            return Path.GetExtension(path);
        }

        /// <summary>
        /// 根据文件路径创建目录
        /// </summary>
        /// <param name="directoryPath">文件路径</param>
        /// <returns></returns>
        public static bool CreateDirectory(string directoryPath)
        {
            if (string.IsNullOrEmpty(directoryPath)) return false;

            if (!Directory.Exists(directoryPath))
            {
                Directory.CreateDirectory(directoryPath);
            }
            return true;
        }

        /// <summary>
        /// 保存文件
        /// </summary>
        /// <param name="directoryPath">文件夹路径</param>
        /// <param name="fileName">文件名</param>
        /// <param name="buffer">缓冲区</param>
        /// <returns>是否成功</returns>
        public static bool SaveFile(string directoryPath, string fileName, byte[] buffer)
        {
            if (string.IsNullOrEmpty(directoryPath))
            {
                throw new Exception("请传入文件夹路径");
            }
            if (string.IsNullOrEmpty(fileName))
            {
                throw new Exception("请传入文件名");
            }
            // 创建对应目录
            CreateDirectory(directoryPath);

            string filePath = Path.Combine(directoryPath, fileName);

            // 如果存在 Excel 文件，先删除文件
            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }
            using (FileStream fs = new FileStream(filePath, FileMode.Create))
            {
                //将byte数组写入文件中
                fs.Write(buffer, 0, buffer.Length);
                //所有流类型都要关闭流，否则会出现内存泄露问题
                fs.Close();
            }

            return true;
        }
    }
}
